/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.remote.channel;

import com.googlecode.actorom.impl.remote.channel.protocol.ClientCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.ServerCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.Ack;
import com.googlecode.actorom.remote.support.RemoteConnectionException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.jcip.annotations.ThreadSafe;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;
import org.jboss.netty.handler.execution.ExecutionHandler;
import org.jboss.netty.handler.execution.MemoryAwareThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class RemoteChannelConnector {

    private static final transient Logger LOG = LoggerFactory.getLogger(RemoteChannelConnector.class);
    private final Lock stateLock = new ReentrantLock();
    private final Map<String, Condition> ackConditions = new HashMap<String, Condition>();
    private final Map<String, Ack> ackCommands = new HashMap<String, Ack>();
    private final String host;
    private final int port;
    private final long timeoutInMillis;
    private final ClientBootstrap client;
    private final ExecutionHandler clientExecutor;
    private Channel clientChannel;

    public RemoteChannelConnector(String host, int port, long timeoutInMillis, ClientCallback callback) {
        this.host = host;
        this.port = port;
        this.timeoutInMillis = timeoutInMillis;
        client = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
        clientExecutor = new ExecutionHandler(new MemoryAwareThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 10, 1048576, 1048576));
        client.setPipelineFactory(new ClientPipelineFactory(clientExecutor, new ClientHandler(callback)));
    }

    public void connect() {
        stateLock.lock();
        try {
            if (clientChannel == null) {
                ChannelFuture future = client.connect(new InetSocketAddress(host, port));
                future.awaitUninterruptibly(timeoutInMillis, TimeUnit.MILLISECONDS);
                if (future.isSuccess()) {
                    LOG.info("Connected to message channel at: {}:{}", host, port);
                    clientChannel = future.getChannel();
                } else {
                    throw new RemoteConnectionException("Error connecting to " + host + ":" + port, future.getCause());
                }
            } else {
                throw new IllegalStateException("Already connected to " + host + ":" + port);
            }
        } finally {
            stateLock.unlock();
        }
    }

    public void disconnect() {
        stateLock.lock();
        try {
            if (clientChannel != null) {
                clientChannel.close();
                clientExecutor.releaseExternalResources();
                client.releaseExternalResources();
                clientChannel = null;
                LOG.info("Disconnected from message channel at: {}:{}", host, port);
            }
        } finally {
            stateLock.unlock();
        }
    }

    public boolean send(ServerCommand command) {
        stateLock.lock();
        try {
            if (clientChannel != null) {
                try {
                    Condition ackCondition = stateLock.newCondition();
                    String ackId = command.getHeader().getCorrelationId();
                    ackConditions.put(ackId, ackCondition);
                    clientChannel.write(command);
                    boolean ok = ackCondition.await(timeoutInMillis, TimeUnit.MILLISECONDS);
                    if (ok) {
                        Ack ack = ackCommands.remove(ackId);
                        return ack.isAcknowledged();
                    } else {
                        LOG.warn("Message not acknowledged: {}", command);
                        ackConditions.remove(ackId);
                        return false;
                    }
                } catch (Exception ex) {
                    LOG.warn(ex.getMessage(), ex);
                    return false;
                }
            } else {
                throw new IllegalStateException("Not connected to " + host + ":" + port);
            }
        } finally {
            stateLock.unlock();
        }
    }

    public boolean isConnected() {
        stateLock.lock();
        try {
            return clientChannel != null;
        } finally {
            stateLock.unlock();
        }
    }

    @Sharable
    private class ClientHandler extends SimpleChannelUpstreamHandler {

        private ClientCallback callback;

        public ClientHandler(ClientCallback callback) {
            this.callback = callback;
        }

        @Override
        public void messageReceived(ChannelHandlerContext context, MessageEvent event) throws Exception {
            Object payload = event.getMessage();
            if (payload instanceof Ack) {
                Ack command = (Ack) payload;
                handleAck(command);
            } else if (payload instanceof ClientCommand) {
                ClientCommand command = (ClientCommand) payload;
                handleCommand(command);
            } else {
                throw new IllegalStateException("Unexpected command of type: " + payload.getClass());
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext context, ExceptionEvent event) throws Exception {
            LOG.debug(event.getCause().getMessage(), event.getCause());
        }

        private void handleAck(Ack command) {
            stateLock.lock();
            try {
                String ackId = command.getHeader().getCorrelationId();
                Condition ackCondition = ackConditions.get(ackId);
                if (ackCondition != null) {
                    ackCommands.put(ackId, command);
                    ackCondition.signalAll();
                }
            } finally {
                stateLock.unlock();
            }
        }

        private void handleCommand(ClientCommand command) {
            command.execute(callback);
        }

    }

    private static class ClientPipelineFactory implements ChannelPipelineFactory {

        private final ExecutionHandler executor;
        private final ClientHandler handler;

        public ClientPipelineFactory(ExecutionHandler executor, ClientHandler handler) {
            this.executor = executor;
            this.handler = handler;
        }

        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast(ObjectEncoder.class.getName(), new ObjectEncoder());
            pipeline.addLast(ObjectDecoder.class.getName(), new ObjectDecoder());
            pipeline.addLast("executor", executor);
            pipeline.addLast(ClientHandler.class.getName(), handler);
            return pipeline;
        }

    }
}
